package logic

import (
	"context"
	"errors"
	"time"

	"go.uber.org/zap"

	"github.com/myblogs/dao/mysql"
	"github.com/myblogs/middlewares"
	"github.com/myblogs/models"
	"github.com/myblogs/pkg/snowflake"
)

var (
	ErrorUserIDExits     = errors.New("获取用户ID失败")
	ErrorAuthorNameExits = errors.New("获取作者名称失败")
)

type ArticleInterface interface {
	CreatedArtical(c context.Context, req *models.ReqArtical) (article *models.Article, err error)
	GetArticleByID(c context.Context, id int64) (*models.Article, error)
	GetArticleByUserID(c context.Context) (*[]models.Article, error)
	DeleteArticle(c context.Context, id int64) error
	GetAllArticles(c context.Context) (*[]models.Article, error)
}
type ArticleLogicImpl struct {
	Art mysql.ArticleDaoInterface
}

func NewArticleLogicImpl(art mysql.ArticleDaoInterface) *ArticleLogicImpl {
	return &ArticleLogicImpl{
		Art: art,
	}
}
func (a *ArticleLogicImpl) CreatedArtical(c context.Context, req *models.ReqArtical) (article *models.Article, err error) {
	// 生成文章ID
	articleID := int64(snowflake.NewSnowflake(time.Now(), 1).GetID())
	userId, exists := c.Value(middlewares.CtxUserID).(int64)
	if !exists {
		zap.S().Info("获取用户ID失败")
		return nil, ErrorUserIDExits
	}
	authorName, exists := c.Value(middlewares.CtxUserName).(*string)
	if !exists {
		zap.S().Info("获取作者名称失败")
		return nil, ErrorAuthorNameExits
	}

	articleModel := &models.Article{
		Title:      req.Title,
		Content:    req.Content,
		Excerpt:    req.Excerpt,
		Tags:       req.Tags,
		AuthorID:   userId,
		AuthorName: *authorName,
		ArticleID:  articleID,
		Status:     1, // 默认设置为已发布状态
	}
	article, err = a.Art.CreatedArtical(c, articleModel)
	if err != nil {
		return nil, err
	}
	return article, nil
}
func (a *ArticleLogicImpl) GetArticleByID(c context.Context, id int64) (*models.Article, error) {
	article, err := a.Art.GetArticleByID(c, id)
	if err != nil {
		if errors.Is(err, mysql.ErrorArticleNotExits) {
			return nil, mysql.ErrorArticleNotExits
		}
		return nil, err
	}
	return article, nil
}
func (a *ArticleLogicImpl) GetArticleByUserID(c context.Context) (*[]models.Article, error) {
	userId, exists := c.Value(middlewares.CtxUserID).(int64)
	if !exists {
		zap.S().Info("获取用户ID失败")
		return nil, ErrorUserIDExits
	}
	return a.Art.GetArticleByUserID(c, userId)
}
func (a *ArticleLogicImpl) DeleteArticle(c context.Context, id int64) error {
	return a.Art.DeleteArticle(c, id)
}
func (a *ArticleLogicImpl) GetAllArticles(c context.Context) (*[]models.Article, error) {
	return a.Art.GetAllArticles(c)
}
